// 云函数 - 创建活动支付订单（云开发标准版本）
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { activityId, participants, notes } = event

  // 获取当前环境 ID
  const envId = process.env.TCB_ENV
  console.log("当前环境 ID:", envId)
  
  console.log('创建活动支付订单请求:', {
    activityId,
    participants: participants?.length,
    notes,
    openid: wxContext.OPENID
  })
  
  try {
    // 验证用户登录状态
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录'
      }
    }
    
    const userOpenid = wxContext.OPENID
    
    // 验证基本参数
    if (!activityId || !participants || participants.length === 0) {
      return {
        success: false,
        message: '参数不完整：缺少活动ID或参与者信息'
      }
    }
    
    // 验证参与者信息
    for (let i = 0; i < participants.length; i++) {
      const participant = participants[i]
      if (!participant.name || !participant.name.trim()) {
        return {
          success: false,
          message: `第${i + 1}位参与者姓名不能为空`
        }
      }
      if (!participant.phone || !participant.phone.trim()) {
        return {
          success: false,
          message: `第${i + 1}位参与者电话不能为空`
        }
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(participant.phone)) {
        return {
          success: false,
          message: `第${i + 1}位参与者电话格式不正确`
        }
      }
    }
    
    // 获取活动信息
    const activityResult = await db.collection('activities').doc(activityId).get()
    if (!activityResult.data) {
      return {
        success: false,
        message: '活动不存在或已下架'
      }
    }
    
    const activity = activityResult.data
    const activityPrice = activity.price || 0
    
    // 检查参与者是否已报名
    const existingMembers = await db.collection('activity_members')
      .where({
        activityId: activityId
      })
      .get()
    
    // 创建已报名参与者映射
    const existingParticipantMap = new Map()
    existingMembers.data.forEach(member => {
      const key = `${member.name}_${member.phone}`
      existingParticipantMap.set(key, member)
    })
    
    // 分类参与者
    const newParticipants = []
    const existingParticipants = []
    
    participants.forEach(participant => {
      const key = `${participant.name}_${participant.phone}`
      if (existingParticipantMap.has(key)) {
        existingParticipants.push(participant)
      } else {
        newParticipants.push(participant)
      }
    })
    
    // 如果所有参与者都已报名
    if (newParticipants.length === 0) {
      const participantNames = existingParticipants.map(p => p.name).join('、')
      return {
        success: false,
        message: `以下参与者已报名该活动：${participantNames}`,
        existingParticipants: existingParticipants,
        skipCount: existingParticipants.length
      }
    }
    
    // 计算实际支付金额
    const totalAmount = newParticipants.length * activityPrice
    
    // 生成微信支付订单号
    const wechatOrderNo = 'ACT' + Date.now() + Math.random().toString(36).substr(2, 6).toUpperCase()
    
    const now = new Date()
    
    // 创建待支付报名记录
    const registrationResult = await db.collection('activity_registrations').add({
      data: {
        activityId: activityId,
        registrantId: userOpenid,
        participants: newParticipants,
        originalParticipants: participants,
        existingParticipants: existingParticipants,
        totalAmount: totalAmount,
        paymentStatus: 'pending',
        status: 0, // 未生效
        wechatOrderNo: wechatOrderNo,
        paymentMethod: 'wechat',
        notes: notes || '',
        registrationTime: now,
        createdAt: now,
        updatedAt: now
      }
    })
    
    console.log('创建待支付报名记录成功:', registrationResult._id)
    
    // 调用云开发微信支付统一下单API
    try {
      const payResult = await cloud.cloudPay.unifiedOrder({
        body: `活动报名-${activity.eventTitle || activity.title || '活动'}`,
        outTradeNo: wechatOrderNo,
        totalFee: totalAmount * 100, // 单位：分
        envId: envId, // 环境ID
        subMchId: '1724228888', // 子商户号
        tradeType: 'JSAPI',
        openid: userOpenid, // 用户openid
        spbillCreateIp: context.CLIENTIP || '127.0.0.1', // 客户端IP
        functionName: 'activityPayNotify', // 支付回调云函数
        attach: JSON.stringify({
          registrationId: registrationResult._id,
          activityId: activityId
        })
      })

      console.log('云开发支付下单结果:', payResult)

      if (payResult.returnCode === 'SUCCESS' && payResult.resultCode === 'SUCCESS') {
        // 直接返回云开发的支付参数，符合标准做法
        return {
          ...payResult,
          // 附加业务信息供前端使用
          registrationId: registrationResult._id,
          wechatOrderNo: wechatOrderNo,
          totalAmount: totalAmount,
          newParticipantsCount: newParticipants.length,
          existingParticipantsCount: existingParticipants.length
        }
      } else {
        console.error('微信支付下单失败:', payResult)
        return {
          success: false,
          message: '创建支付订单失败: ' + (payResult.errMsg || payResult.returnMsg || '未知错误')
        }
      }
    } catch (payError) {
      console.error('微信支付API调用失败:', payError)
      return {
        success: false,
        message: '支付服务异常，请稍后重试'
      }
    }
    
  } catch (error) {
    console.error('创建活动支付订单失败:', error)
    return {
      success: false,
      message: '创建支付订单失败: ' + error.message
    }
  }
}